var core = require("core");
var step = core.step;
var wechat = core.wechat;
var send = core.send;

var orderConfirm = function(req, res, next){
    var query = req.query;
    var state = query.state ? JSON.parse(query.state) : null;
    var oid = query.oid || state.oid;
    var mid = query.mid || state.mid;
    var code = query.code;
    var template = "open/order";
    var tag_id = wechat.config.tagid_contrast[3];
    var openid, user, order, upMoney, merchant, SEND;

    if(!state){
        res.redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ wechat.config.AppID +"&redirect_uri="+ wechat.config.URL+"open/order_confirm&response_type=code&scope=snsapi_base&state="+JSON.stringify({
            oid : oid,
            mid : mid
        })+"#wechat_redirect");
    }else{
        var getOpenid = function(){
            var that = this;
            var param = {
                appid : wechat.config.AppID,
                secret : wechat.config.AppSecret,
                code : code,
                grant_type : 'authorization_code'
            };
            wechat.api.get('sns/oauth2/access_token', param, function(err, doc){
                that.step({err: err, doc: doc});
            });
        };

        var getOpenidEnd = function(result){
            var that = this;
            var err = result.err;
            var doc = result.doc;

            if(err || doc.errcode){
                template = "admin/error";
                SEND = new send(400000);
                that.end();
            };

            openid = doc.openid;

            return true;
        };

        var getUser = function(){
            var that = this;
            var params = {
                openid : openid,
                merchant : parseInt(mid),
                tagid_list : parseInt(tag_id)
            };
            core.api("user/getUser", params, function(err, doc){
                that.step({err: err, doc: doc});
            });
        };

        var getUserEnd = function(result){
            var that = this;
            var err = result.err;
            var doc = result.doc;
            if(err){
                template = "admin/error";
                SEND = new send(200000);
                return that.end();
            };
            if(doc.code && doc.code !== 100201){
                SEND = doc;
                return that.end();
            }
            if(doc.code){
                template = "admin/error";
                SEND = new send(100002);
                return that.end();
            };

            user = doc.docs;

            return true;
        };

        var getOrder = function(){
            var that = this;
            var params = {
                oid : oid
            };
            core.api("order/get", params, function(err, doc){
                that.step({err: err, doc: doc});
            });
        };

        var getOrderEnd = function(result){
            var that = this;
            var err = result.err;
            var doc = result.doc;

            if(err){
                template = "admin/error";
                SEND = new send(400000);
                that.end();
            };
            if(doc.code){
                template = "admin/error";
                SEND = doc;
                that.end();
            };

            order = doc.docs;

            upMoney = order.money * 0.05;
            upMoney = upMoney < 1 ? 0 : parseInt(upMoney);

            order.money = order.money / 100;
            order.money.toFixed(2);

            if(order.auth_status){
                template = "open/info";
                SEND = new send(100003);
                SEND.docs = {
                    token : null
                }
                that.end();
            };

            return true;

        };

        var upOrder = function(){
            var that = this;
            var params = {
                query : JSON.stringify({oid: oid}),
                update : JSON.stringify({
                    auth_status : true,
                    runMoney : upMoney,
                    sale : openid,
                    auth_time : new Date()
                })
            };
            core.api("order/update", params, function(err, doc){
                that.step({err: err, doc: doc});
            });
        };

        var upOrderEnd = function(result){
            var that = this;
            var err = result.err;
            var doc = result.doc;

            if(err){
                template = "admin/error";
                SEND = new send(200000);
                that.end();
            };
            if(doc.code){
                template = "admin/error";
                SEND = doc;
                that.end();
            };

            return true;
        };

        var setMoney = function(){
            var that = this;
            var params = {
                openid : openid,
                update : JSON.stringify({
                    $inc : {
                        money : upMoney
                    }
                })
            };
            core.api("user/upUser", params, function(err, doc){
                that.step({err: err, doc: doc});
            });
        };

        var setMoneyEnd = function(result){
            var that = this;
            var err = result.err;
            var doc = result.doc;
            if(err){
                template = "admin/error";
                SEND = new send(200000);
                that.end();
            };
            if(doc.code){
                template = "admin/error";
                SEND = doc.docs;
                that.end();
            };

            return true;

        };

        var getMerchant = function(){
            var that = this;
            var params = {
                mid : mid
            };
            core.api("merchant/find", params, function(err, doc){
                that.step({err: err, doc: doc});
            });
        };

        var getMerchantEnd = function(result){
            var err = result.err;
            var doc = result.doc;
            var that = this;
            if(err){
                template = "admin/error";
                SEND = new send(200000);
                return that.end();
            };
            if(doc.code){
                template = "admin/error";
                SEND = doc;
                return that.end();
            };
            var run = false;
            merchant = doc.docs;
            for(var i = 0; i < merchant.personnel.length; i++){
                if(merchant.personnel[i].openid === openid){
                    run = true;
                    break;
                };
            };
            if(!run){
                template = "admin/error";
                SEND = new send(100002);
                return that.end();
            }else
                return run;
        };

        var getRegion = function(){
            var that = this;
            var params = {
                p : merchant.address.area[0],
                c : merchant.address.area[1],
                a : merchant.address.area[2]
            };
            core.api("open/getRegion", params, function(err, doc){
                that.step({err: err, doc: doc});
            });
        };

        var getRegionEnd = function(result){
            var err = result.err;
            var doc = result.doc;
            var that = this;
            if(err){
                template = "admin/error";
                SEND = new send(200000);
                that.end();
            };
            if(doc.code){
                template = "admin/error";
                SEND = doc;
                return that.end();
            };

            merchant.address.area[0] = doc.docs[0].label;
            merchant.address.area[1] = doc.docs[0].children[0].label;
            merchant.address.area[2] = doc.docs[0].children[0].children[0].label;

            return true;
        };

        var end = function(){

            if(!SEND){
                SEND = new send(0);
                SEND.docs = {
                    money : order.money,
                    upMoney : upMoney / 100,
                    oid : order.oid,
                    title : order.body,
                    name : merchant.name,
                    address : merchant.address.area.join("/")+"&nbsp;"+merchant.address.text,
                    heapMoney: user.money / 100
                };
            };
            SEND.docs = SEND.docs || {};
            SEND.docs.jssdk = wechat.getJSSDK(req.originalUrl)

            res.render(template, SEND);

        };

        step.Step(
            getOpenid,
            getOpenidEnd,
            getUser,
            getUserEnd,
            getOrder,
            getOrderEnd,
            upOrder,
            upOrderEnd,
            setMoney,
            setMoneyEnd,
            getMerchant,
            getMerchantEnd,
            getRegion,
            getRegionEnd,
            end
        );

    }
};

module.exports = orderConfirm;
